<template>
  <div>
    <!-- 使用Header组件 -->
    <HeaderComponent 
      :isLoggedIn="isLoggedIn"
      :userInfo="userInfo"
      :showUserPanel="showUserPanel"
      @open-login="$emit('open-login')"
      @toggle-user-panel="$emit('toggle-user-panel')"
      @logout="$emit('logout')"
    />
    
    <div class="article-container">
      <!-- 左侧边栏 -->
      <aside class="sidebar">
        <div class="sidebar-actions">
          <!-- 点赞按钮 -->
          <div class="action-item" @click="toggleLike">
            <div class="action-icon" :class="{ active: isLiked }">
              <span>👍</span>
            </div>
            <span class="action-count">{{ article?.like_count || 0 }}</span>
          </div>
          
          <!-- 评论按钮 -->
          <div class="action-item" @click="scrollToComments">
            <div class="action-icon">
              <span>💬</span>
            </div>
            <span class="action-count">{{ article?.comment_count || 0 }}</span>
          </div>
          
          <!-- 收藏按钮 -->
          <div class="action-item" @click="toggleCollect">
            <div class="action-icon" :class="{ active: isCollected }">
              <span>⭐</span>
            </div>
            <span class="action-count">{{ article?.collect_count || 0 }}</span>
          </div>
          
          <!-- 分享按钮 -->
          <div class="action-item" @click="shareArticle">
            <div class="action-icon">
              <span>📤</span>
            </div>
          </div>
        </div>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-content">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <div class="loading-spinner"></div>
          <p>正在加载文章...</p>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error">
          <h3>加载失败</h3>
          <p>{{ error }}</p>
          <button @click="fetchArticle" class="retry-btn">重试</button>
        </div>

        <!-- 文章内容 -->
        <article v-else-if="article" class="article">
          <!-- 文章头部 -->
          <header class="article-header">
            <h1 class="article-title">{{ article.title }}</h1>
            
            <div class="article-meta">
              <div class="author-info">
                <img src="https://via.placeholder.com/40x40/007fff/FFFFFF?text=A" alt="作者头像" class="author-avatar">
                <div class="author-details">
                  <span class="author-name">{{ article.author || 'CodeJourney' }}</span>
                  <div class="publish-info">
                    <span class="publish-time">{{ formatDate(article.published_at) }}</span>
                    <span class="read-info">
                      <span class="view-icon">👁️</span>
                      {{ article.view_count }} 
                    </span>
                    <span class="read-time">阅读{{ article.reading_time }}分钟</span>
                  </div>
                </div>
              </div>
            </div>
          </header>

          <!-- 文章正文 -->
          <div class="article-content">
            <div class="markdown-body" v-html="renderedContent"></div>
          </div>

          <!-- 文章标签 -->
          <div class="article-tags" v-if="article.seo_keywords">
            <span class="tag" v-for="tag in article.seo_keywords.split(',')" :key="tag">
              {{ tag.trim() }}
            </span>
          </div>
        </article>

        <!-- 评论区域 -->
        <section class="comments-section" ref="commentsSection" v-if="article">
          <div class="comments-header">
            <h3>评论 {{ comments.length }}</h3>
          </div>
          
          <!-- 评论输入框 -->
          <div class="comment-input-area">
            <div class="comment-input-wrapper">
              <img src="https://via.placeholder.com/40x40/FF6B6B/FFFFFF?text=U" alt="用户头像" class="user-avatar">
              <div class="comment-input-box">
                <textarea 
                  v-model="newComment" 
                  placeholder="论首评，友善交流"
                  class="comment-textarea"
                  @keydown.ctrl.enter="submitComment"
                ></textarea>
                <div class="comment-actions">
                  <div class="comment-tools">
                    <button class="tool-btn">😊</button>
                    <button class="tool-btn">📷</button>
                  </div>
                  <div class="comment-submit">
                    <span class="char-count">{{ newComment.length }} / 1000</span>
                    <button 
                      class="submit-btn" 
                      :disabled="!newComment.trim()" 
                      @click="submitComment"
                    >
                      发表
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comments-list">
            <div v-if="comments.length === 0" class="no-comments">
              <div class="no-comments-icon">🐦</div>
              <p>暂无评论数据</p>
            </div>
            <div v-else>
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                <img :src="comment.avatar || '/touxiang.jpg'" alt="用户头像" class="comment-avatar">
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.author }}</span>
                    <span class="comment-time">{{ formatDate(comment.created_at) }}</span>
                  </div>
                  <div class="comment-text">{{ comment.content }}</div>
                  <div class="comment-actions">
                    <button class="comment-action-btn" @click="likeComment(comment)">
                      <span>👍</span>
                      <span v-if="comment.like_count > 0">{{ comment.like_count }}</span>
                    </button>
                    <button class="comment-action-btn" @click="replyComment(comment)">
                      回复
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import api from '@/api'
import HeaderComponent from '@/components/HeaderComponent.vue'
import MarkdownIt from 'markdown-it'

export default {
  name: 'ArticleDetail',
  components: {
    HeaderComponent
  },
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default: () => ({
        username: '',
        avatar: ''
      })
    },
    showUserPanel: {
      type: Boolean,
      default: false
    }
  },
  emits: ['open-login', 'toggle-user-panel', 'logout'],
  setup() {
    const route = useRoute()
    const article = ref(null)
    const loading = ref(false)
    const error = ref(null)
    const comments = ref([])
    const newComment = ref('')
    const isLiked = ref(false)
    const isCollected = ref(false)
    const commentsSection = ref(null)

    // 初始化 markdown 渲染器
    const md = new MarkdownIt({
      html: true,
      linkify: true,
      typographer: true
    })

    // 渲染后的内容
    const renderedContent = computed(() => {
      if (!article.value?.content) return ''
      return md.render(article.value.content)
    })

    // 获取文章详情
    const fetchArticle = async () => {
      const articleId = route.params.id
      if (!articleId) {
        error.value = '文章ID不存在'
        return
      }

      loading.value = true
      error.value = null

      try {
        const response = await api.article.getDetail(articleId)
        if (response.code === 0) {
          article.value = response.data
          // 模拟获取评论数据
          fetchComments()
        } else {
          error.value = response.message || '获取文章失败'
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试'
        console.error('获取文章详情失败:', err)
      } finally {
        loading.value = false
      }
    }

    // 获取评论数据（模拟）
    const fetchComments = () => {
      // 模拟评论数据
      comments.value = [
        {
          id: 1,
          author: '技术爱好者',
          content: '这篇文章写得很好，学到了很多！',
          created_at: '2025-01-12T10:30:00Z',
          like_count: 5,
          avatar: 'https://via.placeholder.com/40x40/2196F3/FFFFFF?text=T'
        },
        {
          id: 2,
          author: 'AI研究员',
          content: 'NVIDIA Earth-2 确实是一个很有前景的项目，期待更多应用。',
          created_at: '2025-01-12T11:15:00Z',
          like_count: 3,
          avatar: 'https://via.placeholder.com/40x40/9C27B0/FFFFFF?text=A'
        }
      ]
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 点赞功能
    const toggleLike = () => {
      isLiked.value = !isLiked.value
      if (article.value) {
        article.value.like_count += isLiked.value ? 1 : -1
      }
      console.log('点赞文章')
    }

    // 收藏功能
    const toggleCollect = () => {
      isCollected.value = !isCollected.value
      if (article.value) {
        article.value.collect_count += isCollected.value ? 1 : -1
      }
      console.log('收藏文章')
    }

    // 分享功能
    const shareArticle = () => {
      if (navigator.share) {
        navigator.share({
          title: article.value.title,
          text: article.value.summary,
          url: window.location.href
        })
      } else {
        navigator.clipboard.writeText(window.location.href)
        alert('链接已复制到剪贴板')
      }
    }

    // 滚动到评论区
    const scrollToComments = () => {
      if (commentsSection.value) {
        commentsSection.value.scrollIntoView({ behavior: 'smooth' })
      }
    }

    // 提交评论
    const submitComment = () => {
      if (!newComment.value.trim()) return
      
      const comment = {
        id: Date.now(),
        author: '当前用户',
        content: newComment.value,
        created_at: new Date().toISOString(),
        like_count: 0,
        avatar: 'https://via.placeholder.com/40x40/FF6B6B/FFFFFF?text=U'
      }
      
      comments.value.unshift(comment)
      newComment.value = ''
      
      // 更新文章评论数
      if (article.value) {
        article.value.comment_count = (article.value.comment_count || 0) + 1
      }
    }

    // 点赞评论
    const likeComment = (comment) => {
      comment.like_count = (comment.like_count || 0) + 1
    }

    // 回复评论
    const replyComment = (comment) => {
      newComment.value = `@${comment.author} `
      // 滚动到评论输入框
      document.querySelector('.comment-textarea')?.focus()
    }

    onMounted(() => {
      fetchArticle()
    })

    return {
      article,
      loading,
      error,
      comments,
      newComment,
      isLiked,
      isCollected,
      commentsSection,
      renderedContent,
      fetchArticle,
      formatDate,
      toggleLike,
      toggleCollect,
      shareArticle,
      scrollToComments,
      submitComment,
      likeComment,
      replyComment
    }
  }
}
</script>

<style scoped>
.article-container {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  gap: 20px;
  padding: 20px;
  overflow-x: hidden;
}

/* 左侧边栏 */
.sidebar {
  width: 60px;
  position: sticky;
  top: 80px;
  height: fit-content;
}

.sidebar-actions {
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.action-item:hover {
  background-color: #f5f5f5;
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  font-size: 18px;
  transition: all 0.2s;
}

.action-icon.active {
  background-color: #007fff;
  color: white;
  border-color: #007fff;
}

.action-count {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  min-width: 0;
  max-width: calc(100% - 80px); /* 减去侧边栏宽度 */
  overflow-wrap: break-word;
}

/* 文章样式 */
.article {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
}

.article-header {
  margin-bottom: 32px;
}

.article-title {
  font-size: 32px;
  font-weight: 700;
  line-height: 1.3;
  color: #1d2129;
  margin: 0 0 20px 0;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
  word-break: break-word;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 600;
  color: #1d2129;
  font-size: 14px;
}

.publish-info {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
  color: #86909c;
}

.view-icon {
  margin-right: 4px;
}

/* 文章内容 */
.article-content {
  margin-bottom: 32px;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
  word-break: break-word;
}

.markdown-body {
  line-height: 1.8;
  font-size: 16px;
  color: #1d2129;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
  word-break: break-word;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3 {
  margin: 32px 0 16px 0;
  font-weight: 600;
  color: #1d2129;
}

.markdown-body h1 {
  font-size: 28px;
  border-bottom: 2px solid #e9ecef;
  padding-bottom: 8px;
}

.markdown-body h2 {
  font-size: 24px;
}

.markdown-body h3 {
  font-size: 20px;
}

.markdown-body p {
  margin: 16px 0;
}

.markdown-body code {
  background: #f8f9fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 14px;
}

.markdown-body pre {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 16px 0;
  max-width: 100%;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.markdown-body blockquote {
  border-left: 4px solid #007fff;
  padding-left: 16px;
  margin: 16px 0;
  color: #666;
  font-style: italic;
}

/* 标签 */
.article-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 32px;
}

.tag {
  background: #f0f8ff;
  color: #007fff;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

/* 评论区域 */
.comments-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
}

.comments-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
  margin: 0 0 24px 0;
}

/* 评论输入 */
.comment-input-area {
  margin-bottom: 32px;
}

.comment-input-wrapper {
  display: flex;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  flex-shrink: 0;
}

.comment-input-box {
  flex: 1;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.comment-textarea {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: none;
  outline: none;
  resize: vertical;
  font-size: 14px;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.comment-tools {
  display: flex;
  gap: 8px;
}

.tool-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.tool-btn:hover {
  background: #e9ecef;
}

.comment-submit {
  display: flex;
  align-items: center;
  gap: 12px;
}

.char-count {
  font-size: 12px;
  color: #86909c;
}

.submit-btn {
  background: #007fff;
  color: white;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.submit-btn:disabled {
  background: #e9ecef;
  color: #86909c;
  cursor: not-allowed;
}

/* 评论列表 */
.no-comments {
  text-align: center;
  padding: 60px 20px;
  color: #86909c;
}

.no-comments-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #1d2129;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #86909c;
}

.comment-text {
  color: #1d2129;
  line-height: 1.6;
  margin-bottom: 12px;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
  word-break: break-word;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.comment-action-btn {
  background: none;
  border: none;
  color: #86909c;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.comment-action-btn:hover {
  background: #f5f5f5;
  color: #1d2129;
}

/* 加载和错误状态 */
.loading {
  text-align: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  text-align: center;
  padding: 60px 20px;
  color: #e74c3c;
}

.retry-btn {
  background: #007fff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 20px;
}

.retry-btn:hover {
  background: #0056b3;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-container {
    flex-direction: column;
    padding: 15px;
  }
  
  .sidebar {
    width: 100%;
    position: static;
    order: 2;
  }
  
  .sidebar-actions {
    flex-direction: row;
    justify-content: center;
    gap: 20px;
  }
  
  .main-content {
    order: 1;
  }
  
  .article-title {
    font-size: 24px;
  }
  
  .comment-input-wrapper {
    flex-direction: column;
  }
}
</style>